package com.sunwoda.springbootredis.redislock.impl;

import com.sunwoda.springbootredis.redislock.RedisLock;
import com.sunwoda.springbootredis.redislock.RedisLock2;
import com.sunwoda.springbootredis.util.RedisBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @program: springbootredis
 * @description: reids
 * @author: SGR
 * @create: 2021-09-15 09:09
 **/
@Slf4j
public class RedisLockImpl2 implements RedisLock2 {

    /** 
    * @Description: 加锁 
    * @Param:  
    * @return:  
    * @Author: SGR 
    * @Date: 2021-09-15 
    */
    @Override
    public boolean tryLock(String key, String value, long timeout, TimeUnit timeUnit) {
        RedisTemplate redisTemplate = RedisBean.redis;
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate.opsForValue().setIfAbsent(key,value,timeout,timeUnit);
    }

    /** 
    * @Description: 释放锁 (键和值是一致的才能释放锁)
    * @Param:  
    * @return:  
    * @Author: SGR 
    * @Date: 2021-09-15 
    */
    @Override
    public void releaseLock(String key, String value) {
        RedisTemplate redisTemplate = RedisBean.redis;
        if (redisTemplate.opsForValue().get(key).equals(value)){
            redisTemplate.delete(key);
        }
    }
}
